package com.timguan.render.service.common;

import com.timguan.common.cache.common.CloseUtil;
import com.timguan.common.cache.common.ConfLoaderUtil;
import com.timguan.common.cache.manager.CacheManager;
import com.timguan.common.cache.manager.CacheManagerUtil;
import com.timguan.common.cache.service.CacheConfig;
import com.timguan.common.cache.service.CacheConfigHelper;
import com.timguan.common.cache.service.ConcurrentCacheHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by guankaiqiang on 16/9/6.
 */
public class CacheService {
    private Logger logger = LoggerFactory.getLogger(CacheService.class);
    private ConcurrentCacheHelper concurrentCacheHelper = null;
    private Map<String, CacheConfig.ServiceCacheConfig> serviceCacheConfigs = new HashMap<String, CacheConfig.ServiceCacheConfig>();

    public void setConcurrentCacheHelper(String cacheConfigLocation) {
        //memcache redis 等客户端初始化
        ConfLoaderUtil confLoaderUtil = ConfLoaderUtil.newInstance().load(cacheConfigLocation);
        CacheManager cacheManager = CacheManagerUtil.getCacheManager(confLoaderUtil);
        this.concurrentCacheHelper = new ConcurrentCacheHelper(cacheManager);
    }

    public ConcurrentCacheHelper getConcurrentCacheHelper() {
        return concurrentCacheHelper;
    }

    public void setServiceCacheConfigs(String serviceCacheConfigLocation) {
        //读取静态的缓存配置(xml中加载)
        InputStream in = null;
        try {
            in = CacheConfigHelper.class.getResourceAsStream(serviceCacheConfigLocation);
            List<CacheConfig.ServiceCacheConfig> cacheConfigList = CacheConfig.loadFromXmlConfig(in).getServiceCacheConfigs();
            if (cacheConfigList != null && cacheConfigList.size() != 0) {
                for (CacheConfig.ServiceCacheConfig cacheConfig : cacheConfigList) {
                    this.serviceCacheConfigs.put(cacheConfig.getCacheKey(), cacheConfig);
                }
            } else {
                logger.warn("[Cache]未设置缓存静态配置!");
            }
        } catch (Exception e) {
            throw new RuntimeException("can't find " + serviceCacheConfigLocation + "!", e);
        } finally {
            CloseUtil.close(in);
        }
    }

    public CacheConfig.ServiceCacheConfig getServiceCacheConfig(String cacheKey) {
        return this.serviceCacheConfigs.get(cacheKey);
    }
}
